axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const tb = document.querySelector('#tb')
const renderBooks = async function () {
  const { data: res } = await axios({
    url: '/api/getbooks',
    method: 'GET',
  })
  const { data } = res
  // console.log(res)
  const html = data
    .map((item) => {
      return ` <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id='${item.id}'>删除</a></td>
    </tr>`
    })
    .join('')
  tb.innerHTML = html
}
renderBooks()
const form = document.querySelector('#bookForm')
form.addEventListener('submit', async function (e) {
  e.preventDefault()

  const data = serialize(form, { hash: true })
  const { data: res } = await axios({
    url: '/api/addbook',
    method: 'POST',
    data,
  })
  alert(res.msg)
  if (res.status !== 201) return
  form.reset()
  // console.log(res)
  renderBooks()
})
tb.addEventListener('click', async function (e) {
  if (e.target.tagName === 'A') {
    // console.log(1)
    let id = e.target.dataset.id
    const { item } = await axios({
      url: '/api/delbook',
      method: 'GET',
      params: { id },
    })
    console.log(item)
    renderBooks()
  }
})
